package com.zhongxi.guoyuan.view.beautifulStore;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulStore.BeautifulStoreData;
import com.zhongxi.guoyuan.entity.beautifulStore.JsonBean;
import com.zhongxi.guoyuan.entity.beautifulStore.MyPayResult;
import com.zhongxi.guoyuan.entity.beautifulStore.PayOrderData;
import com.zhongxi.guoyuan.entity.beautifulStore.PayOrderInfo;
import com.zhongxi.guoyuan.entity.beautifulStore.PayOrderResult;
import com.zhongxi.guoyuan.entity.beautifulStore.ServiceInfoResult;
import com.zhongxi.guoyuan.entity.pay.PayAliPayData;
import com.zhongxi.guoyuan.entity.pay.WeixinData;
import com.zhongxi.guoyuan.entity.user.center.UserExtendResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DesTool;
import com.zhongxi.guoyuan.utils.JsonUtils;
import com.zhongxi.guoyuan.utils.MD5Tool;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.PaySuccessActivity;
import com.zhongxi.guoyuan.weixin.MD5;
import com.zhongxi.guoyuan.weixin.Util;
import com.zhongxi.guoyuan.zhifubao.PayResult;
import com.zhongxi.guoyuan.zhifubao.SignUtils;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class OrderActivity extends BaseActivity implements View.OnClickListener {


    private String orderid;
    private String type;
    private Map<String, String> map = new HashMap<String, String>();
    private PayOrderResult result;
    private ImageView ivImg;
    private TextView tvProjectName;
    private TextView tvTime;
    private TextView workmanship;
    private TextView tvCash;
    private TextView tvNum;
    private TextView tvDistance;
    private String trueInner = "0";
    private String trueRedBean = "0";
    private String trueCash = "0";
    private ImageView ivShopImg;
    private TextView tvShopName;
    private TextView tvShopAddress;
    private RatingBar ratingBar;
    private TextView ratingbar_score;
    private ImageView checkbox;
    private TextView order_projectCost;
    private TextView order_existing;
    private EditText order_etPassword;
    private TextView tvOrder;

    private RelativeLayout relaEnough;
    private RelativeLayout relaNotEnough;
    private TextView redBeanPaid;
    private UserExtendResult userExtendResult;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的一部通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();//同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //判断resultStatus为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //该笔订单是否真实支付成功，需要依赖服务端的异步通知
                        Intent intent = new Intent(context, PaySuccessActivity.class);
                        intent.putExtra("status", 1);
                        startActivity(intent);
                    } else {
                        startAct(PaySuccessActivity.class);
                    }
                    break;
            }
        }
    };

    private StringBuffer sb;
    private Map<String, String> resultunifiedorder;
    private PayReq req;
    //    private PayParamsResult paramsResult;
    private TextView tvOriginPrice;
    private String viewnum;
    private String redBeanCurrency;
    private String innerCurrency;
    private String trim;
    private PayAliPayData aliPayData;
    private WeixinData weixinData;
    private TextView order_service_cancle;
    private TextView order_service_know;
    private ArrayList<String> orderidList;
    private String orderNum = "1";
    private ServiceInfoResult.ServiceData serviceData;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_order);
        initTitle();
        tvTitle.setText("美容支付");
        orderid = getIntent().getStringExtra("orderid");
        viewnum = getIntent().getStringExtra("viewnum");

        ivImg = (ImageView) findViewById(R.id.ivImg);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvProjectName = (TextView) findViewById(R.id.tvProjectName);
        tvOriginPrice = (TextView) findViewById(R.id.tvOriginPrice);
        workmanship = (TextView) findViewById(R.id.workmanship);
        tvCash = (TextView) findViewById(R.id.tvCash);
        tvNum = (TextView) findViewById(R.id.tvNum);

        ivShopImg = (ImageView) findViewById(R.id.ivShopImg);
        tvShopName = (TextView) findViewById(R.id.tvShopName);
        tvShopAddress = (TextView) findViewById(R.id.tvShopAddress);
        tvDistance = (TextView) findViewById(R.id.tvDistance);
        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        ratingbar_score = (TextView) findViewById(R.id.ratingbar_score);
        checkbox = (ImageView) findViewById(R.id.checkbox);
        checkbox.setVisibility(View.INVISIBLE);

        relaEnough = (RelativeLayout) findViewById(R.id.rela_beauty_enough);
        relaNotEnough = (RelativeLayout) findViewById(R.id.rela_beauty_notEnough);

        redBeanPaid = (TextView) findViewById(R.id.redbean_paid);

        order_service_cancle = (TextView) findViewById(R.id.order_service_cancle);
        order_service_know = (TextView) findViewById(R.id.order_service_know);

        order_projectCost = (TextView) findViewById(R.id.order_projectCost);
        order_etPassword = (EditText) findViewById(R.id.order_etPassword);
        order_existing = (TextView) findViewById(R.id.order_existing);
        tvOrder = (TextView) findViewById(R.id.tvOrder);

        ratingBar.setIsIndicator(true);
        checkbox.setVisibility(View.GONE);

        relaEnough.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle orderidInfo = getIntent().getBundleExtra("orderidInfo");
        if (orderidInfo != null) {
            getGoodShopInfo(orderidInfo);
        }
        if (!TextUtils.isEmpty(orderid)) {
            type = "topay";    //未支付的订单
            String str = "&orderid=" + orderid;
            getServer(Url.TO_PAY, null, str, false, null, "get");
        }
    }

    private void getGoodShopInfo(Bundle orderidInfo) {
        orderNum = orderidInfo.getString("orderNum");
        tvNum.setText("X " + orderNum);
        serviceData = (ServiceInfoResult.ServiceData) orderidInfo.getSerializable("goodInfo");
        BeautifulStoreData storeData = (BeautifulStoreData) orderidInfo.getSerializable("shopInfo");
        orderidList = orderidInfo.getStringArrayList("orderidList");
        PayOrderData service = new PayOrderData();
        if (serviceData.getImages() != null && serviceData.getImages().size() > 0) {
            service.setThumbnail(serviceData.getImages().get(0));
        } else if (!TextUtils.isEmpty(serviceData.getThumbnail())) {
            service.setThumbnail(serviceData.getThumbnail());
        }
        service.setMarketprice(serviceData.getMarketprice());
        service.setServicetime(serviceData.getServicetime());
        service.setItemname(serviceData.getName());
        service.setShouldinnerprice(serviceData.getInnerprice());
        service.setShouldredbeanprice(serviceData.getRedbeanprice());
        service.setViewnum(serviceData.getViewnum());

        PayOrderInfo shopInfo = new PayOrderInfo();
        shopInfo.setName(storeData.getName());
        shopInfo.setAddress(storeData.getAddress());
        shopInfo.setStarlevel(storeData.getStarlevel());
        shopInfo.setThumbnail(storeData.getThumbnail());
        shopInfo.setLongitude(storeData.getLongitude());
        shopInfo.setDimensions(storeData.getDimensions());
        setData(service, shopInfo);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvOrder.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvOrder:
                trim = order_etPassword.getText().toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    getVerifycode();
                } else {
                    showShortToast("请输入密码");
                }
                break;
            case R.id.order_service_cancle:
                // 取消订单
                map.clear();
                map.put("orderid", orderid);
                type = "cancleOrder";
                getServer(Url.CANCLENOPAYORDER, map, "", false, null, "post");
                break;
            case R.id.order_service_know:
                //我知道了
                finish();
                break;
        }
    }

    /**
     * 支付校验
     *
     * @param verifycode
     */
    private void verifypay(String verifycode) {
        if (!TextUtils.isEmpty(trim)) {
            map.clear();
            type = "verifyPay";
            map.put("pwd", MyApplication.getInstance().descsc(trim));
            map.put("verifycode", verifycode);
            map.put("details", getJsonStr());
            getServer(Url.VERIFY_PAY, map, "", false, null, "post");   //服务器需要修改传参的美币
        } else {
            showShortToast("请输入密码");
        }
    }

    private void getVerifycode() {
        type = "verifyCode";
        getServer(Url.MY_EXTEND_INFO, null, "", false, null, "get");
    }

    /**
     * 获取支付校验json参数字符串
     *
     * @return
     */
    private String getJsonStr() {
        try {
            JsonBean jsonBean = new JsonBean();
            if (TextUtils.isEmpty(orderid)) {
                jsonBean.setSid(serviceData.getId());
                jsonBean.setOrderid(orderidList);
                jsonBean.setShouldinnerprice(DataUtil.multiplys(serviceData.getInnerprice(), orderNum,2));
                jsonBean.setShouldredbeanprice(DataUtil.multiplys(serviceData.getRedbeanprice(), orderNum,2));
            } else {
                jsonBean.setSid(result.getService().getItemid());
                List<String> lists = new ArrayList<>();
                lists.add(orderid);
                jsonBean.setOrderid(lists);
                jsonBean.setShouldinnerprice(result.getService().getShouldinnerprice());
                jsonBean.setShouldredbeanprice(result.getService().getShouldredbeanprice());
            }
            jsonBean.setInnerprice(trueInner);
            jsonBean.setRedbeanprice(trueRedBean);
            jsonBean.setPrice(trueCash);
            String toJson = new Gson().toJson(jsonBean);
            return MyApplication.getInstance().descsc(toJson);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("topay".equals(type)) {
                result = gson.fromJson(response, PayOrderResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                setData(result.getService(), result.getShopInfo());
            } else if ("verifyCode".equals(type)) {
                userExtendResult = gson.fromJson(response, UserExtendResult.class);
                MyApplication.getInstance().setSpValue(userExtendResult.getSafeobj());
                if (null != userExtendResult.getVerifycode() && !"".equals(userExtendResult.getVerifycode())) {
                    verifypay(userExtendResult.getVerifycode());
                } else {
                    showShortToast("支付失败");
                }
            } else if ("verifyPay".equals(type)) {
                MyPayResult myPayResult = gson.fromJson(response, MyPayResult.class);
                MyApplication.getInstance().setSpValue(myPayResult.getSafeobj());
                if (null != myPayResult.getSecurityKey() && !"".equals(myPayResult.getSecurityKey())) {
                    String payParams = parseSecutiryKey(myPayResult.getSecurityKey());
//                paramsResult = gson.fromJson(payParams, PayParamsResult.class);
                    JSONObject jsonObject = new JSONObject(payParams);
                    JSONObject alipay = jsonObject.optJSONObject("alipay");
                    aliPayData = PayAliPayData.parseObject(alipay);
                    JSONObject wechat = jsonObject.optJSONObject("wechat");
                    weixinData = WeixinData.parseObject(wechat);
                }
                if (TextUtils.isEmpty(orderid)) {
                    if (DataUtil.moreThanOtherNoEqual(redBeanCurrency, DataUtil.multiplys(serviceData.getRedbeanprice(), orderNum,2))) {
                        //美豆红豆足够
                        showPaySuccessful();
                    } else {
                        //美豆足够，红豆不够
                        String subtract = DataUtil.subtract(DataUtil.multiplys(serviceData.getRedbeanprice(), orderNum,2), redBeanCurrency);
                        MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "beauty").commit();
                        showHongdouNoBalance(subtract);
                    }
                } else {
                    if (DataUtil.moreThanOther(redBeanCurrency, result.getService().getShouldredbeanprice())) {
                        //美豆红豆足够
                        showPaySuccessful();
                    } else {
                        //美豆足够，红豆不够
                        String subtract = DataUtil.subtract(result.getService().getShouldredbeanprice(), redBeanCurrency);
                        MyApplication.getInstance().sharedPrefrences.edit().putString("pay", "beauty").commit();
                        showHongdouNoBalance(subtract);
                    }
                }
            } else if ("cancleOrder".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("订单删除成功");
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        }
        if (result.getCode() == 1000) {
            showShortToast("参数错误！");
        } else if (result.getCode() == 1001) {
            showShortToast("未登录用户");
        } else if (result.getCode() == 1201) {
            showShortToast("店铺关闭");
            finish();
        } else if (result.getCode() == 5001) {
            showShortToast("美豆不足，不能预约");
        } else if (result.getCode() == 5002) {
            showShortToast("服务项目已下架");
        } else if (result.getCode() == 1668) {
            showShortToast("支付金额错误");
        } else if (result.getCode() == 1669) {
            showShortToast("红豆不足");
        } else if (result.getCode() == 1680) {
            showShortToast("用户扩展信息变更， 请重新加载用户扩展接口");
        } else if (result.getCode() == 1681) {
            showShortToast("不能删除已支付订单");
        } else if (result.getCode() == 4003) {
            showShortToast("密码错误");
        } else if (result.getCode() == 5003) {
            showShortToast("美豆不足");
        }
    }

    private void setData(PayOrderData service, PayOrderInfo shopInfo) {

        if (null != service && !"".equals(service)) {
            Glide.with(context).load(Url.IMG_URL + service.getThumbnail()).placeholder(R.mipmap.iv_eg).into(ivImg);
            if (null != service.getServicetime() && !"".equals(service.getServicetime())) {
                tvTime.setText(service.getServicetime() + " 分钟");
            } else {
                tvTime.setText("");
            }
            if (null != service.getItemname() && !"".equals(service.getItemname())) {
                tvProjectName.setText(service.getItemname());
            } else {
                tvProjectName.setText("");
            }
            if (null != service.getMarketprice() && !"".equals(service.getMarketprice())) {
                tvOriginPrice.setText("市场价：" + service.getMarketprice() + " 元");
                tvOriginPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
                tvOriginPrice.setText("");
            }
            if (null != service.getShouldinnerprice() && !"".equals(service.getShouldinnerprice())) {
                tvCash.setText(service.getShouldinnerprice() + " 美豆");
                order_projectCost.setText(DataUtil.divide(DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2), "1", 0) + " 美豆");
            } else {
                tvCash.setText("");
                order_projectCost.setText("");
            }
            if (null != service.getShouldredbeanprice() && !"".equals(service.getShouldredbeanprice())) {
                workmanship.setText("+" + service.getShouldredbeanprice() + " 红豆");
                redBeanPaid.setText("+" + DataUtil.multiplys(service.getShouldredbeanprice(), orderNum,2) + " 红豆");
            } else {
                workmanship.setText("");
                redBeanPaid.setText("");
            }

            String hdCurrency = MyApplication.getInstance().getHdCurrency();
            int indexOf = hdCurrency.lastIndexOf(".");
            //当前拥有的红豆
            redBeanCurrency = hdCurrency.substring(0, indexOf);
            //当前的美豆
            innerCurrency = MyApplication.getInstance().getInnerCurrency();

            order_existing.setText("您目前现存:" + MyApplication.getInstance().getInnerCurrency()
                    + " 美豆/" + DataUtil.formatDataSixPoint(MyApplication.getInstance().getHdCurrency()) + "红豆");

            if (TextUtils.isEmpty(orderid)) {
                if (!DataUtil.moreThanOther(innerCurrency, DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2))) {
                    //美豆不够
                    relaEnough.setVisibility(View.GONE);
                    relaNotEnough.setVisibility(View.VISIBLE);
                } else if (DataUtil.moreThanOther(innerCurrency, DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2))
                        && DataUtil.moreThanOther(redBeanCurrency, DataUtil.multiplys(service.getShouldredbeanprice(), orderNum,2))) {
                    //美豆红豆足够
                    trueInner = DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2);
                    trueRedBean = DataUtil.formatDataSixPoint(DataUtil.multiplys(service.getShouldredbeanprice(), orderNum,2));
                    trueCash = "0.00";


                } else if (DataUtil.moreThanOther(innerCurrency, DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2))
                        && !DataUtil.moreThanOther(redBeanCurrency, DataUtil.multiplys(service.getShouldredbeanprice(), orderNum,2)) && DataUtil.moreThanZero(redBeanCurrency)) {
                    //美豆足够，红豆不够
                    trueInner = DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2);
                    trueRedBean = redBeanCurrency;
                    trueCash = DataUtil.subtract(DataUtil.multiplys(service.getShouldredbeanprice(), orderNum,2), redBeanCurrency);
                } else if (!DataUtil.moreThanZero(redBeanCurrency) && DataUtil.moreThanOther(innerCurrency, DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2))) {
                    //没有红豆
                    trueInner = DataUtil.multiplys(service.getShouldinnerprice(), orderNum,2);
                    trueRedBean = "0";
                    trueCash = DataUtil.multiplys(service.getShouldredbeanprice(), orderNum,2);
                }
            } else {
                if (!DataUtil.moreThanOther(innerCurrency, service.getShouldinnerprice())) {
                    //美豆不够
                    relaEnough.setVisibility(View.GONE);
                    relaNotEnough.setVisibility(View.VISIBLE);
                } else if (DataUtil.moreThanOther(redBeanCurrency, service.getShouldredbeanprice()) && DataUtil.moreThanOther(innerCurrency, service.getShouldinnerprice())) {
                    //美豆红豆足够
                    trueInner = service.getShouldinnerprice();
                    trueRedBean = service.getShouldredbeanprice();
                    trueCash = "0.00";
                } else if (!DataUtil.moreThanOther(redBeanCurrency, service.getShouldredbeanprice())
                        && DataUtil.moreThanOther(innerCurrency, service.getShouldinnerprice()) && DataUtil.moreThanZero(redBeanCurrency)) {
                    //美豆足够，红豆不够
                    trueInner = service.getShouldinnerprice();
                    trueRedBean = redBeanCurrency;
                    trueCash = DataUtil.subtract(service.getShouldredbeanprice(), redBeanCurrency);
                } else if (!DataUtil.moreThanZero(redBeanCurrency) && DataUtil.moreThanOther(innerCurrency, service.getShouldinnerprice())) {
                    //没有红豆
                    trueInner = service.getShouldinnerprice();
                    trueRedBean = "0";
                    trueCash = service.getShouldredbeanprice();
                }
            }
        }

        if (null != shopInfo && !"".equals(shopInfo)) {
            if (null != shopInfo.getName() && !"".equals(shopInfo.getName())) {
                tvShopName.setText(shopInfo.getName());
            } else {
                tvShopName.setText("");

            }
            if (null != shopInfo.getThumbnail() && !"".equals(shopInfo.getThumbnail())) {
                Glide.with(this).load(Url.IMG_URL + shopInfo.getThumbnail()).placeholder(R.mipmap.iv_eg).into(ivShopImg);
            }
            if (null != shopInfo.getStarlevel() && !"".equals(shopInfo.getStarlevel())) {
                ratingBar.setRating(Float.parseFloat(shopInfo.getStarlevel()));
                ratingbar_score.setText(shopInfo.getStarlevel());
            } else {
                ratingBar.setRating(0);
                ratingbar_score.setText("");
            }
            if (null != shopInfo.getAddress() && !"".equals(shopInfo.getAddress())) {
                tvShopAddress.setText(shopInfo.getAddress());
            } else {
                tvShopAddress.setText("");
            }
            if (null != shopInfo.getLongitude() && null != shopInfo.getDimensions()) {
                tvDistance.setText(CommonTool.getDistance(Double.parseDouble(shopInfo.getLongitude()),
                        Double.parseDouble(shopInfo.getDimensions()),
                        Double.parseDouble(MyApplication.getInstance().getLongitude()),
                        Double.parseDouble(MyApplication.getInstance().getLatitude())));
            } else {
                tvDistance.setText("定位失败");
            }
        }
    }

    /**
     * 弹出支付成功提醒
     */
    private void showPaySuccessful() {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_order_success, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startAct(MainHomeActivity.class);
            }
        });
    }

    /**
     * 红豆余额不足
     *
     * @param payMoney
     */
    private void showHongdouNoBalance(String payMoney) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_order_hongdou, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView order_tvLess_hongdou = (TextView) layout.findViewById(R.id.order_tvLess_hongdou);
        order_tvLess_hongdou.setText(payMoney + " 红豆");
        TextView order_tvLess_yuan = (TextView) layout.findViewById(R.id.order_tvLess_yuan);
        order_tvLess_yuan.setText(payMoney + " 元");
        LinearLayout ll_aliPay = (LinearLayout) layout.findViewById(R.id.ll_aliPay);
        ll_aliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    zhifubaoPay(aliPayData);  //支付宝
                }
            }
        });
        LinearLayout ll_weichatPay = (LinearLayout) layout.findViewById(R.id.ll_weichatPay);
        ll_weichatPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CommonTool.isFirstLongScroll()) {
                    weixinPay(weixinData);  //微信支付
                }
            }
        });
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        //放弃支付
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });

    }

    private IWXAPI msgApi;

    /**
     * 微信支付
     *
     * @param wechat
     */
    private void weixinPay(WeixinData wechat) {
        msgApi = WXAPIFactory.createWXAPI(this, wechat.getAppid());
        // 将该app注册到微信
        msgApi.registerApp(wechat.getAppid());
        getWXOrderInfo();
    }

    /**
     * 获取微信支付订单
     */
    private void getWXOrderInfo() {
        //正常情况下，请求服务器获取订单参数
        req = new PayReq();
        sb = new StringBuffer();
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();
    }

    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {


        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(context, getString(R.string.app_tip), getString(R.string.getting_prepayid));
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");
            resultunifiedorder = result;
            genPayReq();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();

            Log.e("orion", entity);

            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            Log.e("orion", content);
            Map<String, String> xml = decodeXml(content);

            return xml;
        }

    }

    private void genPayReq() {

        req.appId = weixinData.getAppid();
        req.partnerId = weixinData.getSeller();
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n" + req.sign + "\n\n");

//        showShortToast("sb:"+sb.toString());
        Log.e("orion", signParams.toString());

        msgApi.sendReq(req);

    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", appSign);
        return appSign;
    }

    private String genOutTradNo() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();
        try {
            String nonceStr = genNonceStr();
            String trade = "";
            if (TextUtils.isEmpty(orderid)) {
                if ((orderidList.get(0) + genOutTradNo()).length() > 32) {
                    trade = (orderidList.get(0) + genOutTradNo()).substring(0, 32);
                } else {
                    trade = orderidList.get(0) + genOutTradNo();
                }
            } else {
                if ((orderid + genOutTradNo()).length() > 32) {
                    trade = (orderid + genOutTradNo()).substring(0, 32);
                } else {
                    trade = orderid + genOutTradNo();
                }
            }

            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", weixinData.getAppid()));
            if (TextUtils.isEmpty(orderid)) {
                String orders = "";
                for (int i = 0; i < orderidList.size(); i++) {
                    orders = orders + orderidList.get(i) + ",";
                }
                packageParams.add(new BasicNameValuePair("attach", getTimeValue() + "||" + MyApplication.getInstance().getUserId() + "||"
                        + orders.substring(0, orders.length() - 1) + "||1||" + trueInner + "," + trueRedBean + "," + trueCash));
                packageParams.add(new BasicNameValuePair("body", serviceData.getName()));
            } else {
                packageParams.add(new BasicNameValuePair("attach", getTimeValue() + "||" + MyApplication.getInstance().getUserId() + "||"
                        + orderid + "||1||" + trueInner + "," + trueRedBean + "," + trueCash));
                packageParams.add(new BasicNameValuePair("body", result.getService().getItemname()));
            }
            packageParams.add(new BasicNameValuePair("mch_id", weixinData.getSeller()));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", Url.BASE_URL + "/notify/pay/wepay"));  //wepay
            packageParams.add(new BasicNameValuePair("out_trade_no", trade));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", MyApplication.getInstance().getLocalIPAddress()));
            BigDecimal bd = new BigDecimal(trueCash);
            packageParams.add(new BasicNameValuePair("total_fee", bd.multiply(new BigDecimal(100)).intValue() + ""));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));

            String xmlstring = toXml(packageParams);
            return new String(xmlstring.toString().getBytes(), "ISO8859-1");

        } catch (Exception e) {
            return null;
        }
    }

    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");


            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        Log.e("orion", sb.toString());
        return sb.toString();
    }

    public Map<String, String> decodeXml(String content) {
        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            //实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("orion", e.toString());
        }
        return null;

    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成签名（微信）
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinData.getPartner());

        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.e("orion", packageSign);
        return packageSign;
    }


    /**
     * 解析后台返回的支付商户信息
     *
     * @param securityKey
     */
    private String parseSecutiryKey(String securityKey) {
        String jsonStr = "";
        try {
            String sourcestr = MD5Tool.Md5(MyApplication.getInstance().getSk() + MyApplication.getInstance().getNow());
            String str = URLDecoder.decode(securityKey, "UTF-8");
            jsonStr = DesTool.splitdecode(sourcestr, str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    /**
     * 支付宝支付
     *
     * @param alipay
     */
    private void zhifubaoPay(PayAliPayData alipay) {

        String orderInfo = getOrderInfo(alipay);

        //  特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中

        String sign = sign(orderInfo, alipay.getRsaPrivate());
        try {
            //仅需对sign做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(OrderActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = 0;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    // create the order info. 创建订单信息（支付宝）
    private String getOrderInfo(PayAliPayData alipay) {

        String trade = "";
        if (TextUtils.isEmpty(orderid)) {
            if ((orderidList.get(0) + genOutTradNo()).length() > 32) {
                trade = (orderidList.get(0) + genOutTradNo()).substring(0, 32);
            } else {
                trade = orderidList.get(0) + genOutTradNo();
            }
        } else {
            if ((orderid + genOutTradNo()).length() > 32) {
                trade = (orderid + genOutTradNo()).substring(0, 32);
            } else {
                trade = orderid + genOutTradNo();
            }
        }

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + alipay.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alipay.getSeller() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + trade + "\"";

        if (TextUtils.isEmpty(orderid)) {
            // 商品名称
            orderInfo += "&subject=" + "\"" + serviceData.getName() + "\"";
            String orders = "";
            for (int i = 0; i < orderidList.size(); i++) {
                orders = orders + orderidList.get(i) + ",";
            }
            // 商品详情
            orderInfo += "&body=" + "\"" + getTimeValue() + "||" + MyApplication.getInstance().getUserId() + "||"
                    + orders.substring(0, orders.length() - 1) + "||1||" + trueInner + "," + trueRedBean + "," + trueCash + "\"";
        } else {
            // 商品名称
            orderInfo += "&subject=" + "\"" + result.getService().getItemname() + "\"";

            // 商品详情
            orderInfo += "&body=" + "\"" + getTimeValue() + "||" + MyApplication.getInstance().getUserId() + "||"
                    + orderid + "||1||" + trueInner + "," + trueRedBean + "," + trueCash + "\"";
        }
        // 商品金额
        orderInfo += "&total_fee=" + "\"" + trueCash + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + Url.BASE_URL + "/notify/pay/alipay" + "\"";   //api3

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"" + Url.BASE_URL + "\"";
        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名（支付宝）
     *
     * @param content 待签名订单信息
     */
    private String sign(String content, String rsa_private) {
        return SignUtils.sign(content, rsa_private);
    }

    /**
     * get the sign type we use. 获取签名方式（支付宝）
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * 获取当前时间戳
     *
     * @return
     */
    private String getTimeValue() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String str = sdf.format(date);
        return str;
    }

}